package com.linkoog.devtools.code_generator.template.render.engine.velocity.directive;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import java.io.IOException;
import java.io.Writer;

/**
 * 分割后，取最后一个元素
 * #Append('#ABC 456' ' ')  => 456
 */
public class SplitAndGetLastOne extends Directive {
    @Override
    public String getName() {
        return "SplitAndGetLastOne";
    }

    @Override
    public int getType() {
        return LINE;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        String value = (String) node.jjtGetChild(0).value(context);
        String split = (String) node.jjtGetChild(1).value(context);

        String retVal;
        int lastInx = value.lastIndexOf(split);
        if (lastInx == -1){
            retVal = value;
        } else {
            retVal = value.substring(lastInx + 1);
        }

        writer.write(retVal);
        return true;
    }
}
